package com.qd.system.service.person;

import com.cdqidi.exception.ApiException;
import com.cdqidi.util.SpringContextHolder;
import com.qd.common.sys.domain.entity.login.LoginUserDTO;
import com.qd.common.sys.domain.entity.role.RoleDTO;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.common.sys.enums.DataScopeType;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.system.treecl.TreeClDTO;
import com.qd.system.treecl.TreeClModel;
import com.qd.system.treecl.TreeClService;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author sjk
 */
public class OrgValidService {
    private OrgValidService() {

    }

    public static void validOperatorByOrgId(String orgId) {
        if (!isOperatorByOrgId(orgId)) {
            throw new ApiException("没有权限操作[" + orgId + "]");
        }
    }

    public static boolean isOperatorByOrgId(String orgId) {
        final LoginUser loginUser = SecurityUtils.getLoginUser();
        final LoginUserDTO user = loginUser.getUser();
        final List<RoleDTO> roles = user.getRoles();
        boolean isCurrentOrg = true;
        final String currentOrgId = loginUser.getCurrentOrgId();
        if (null == roles || roles.isEmpty()) {
            if (SecurityUtils.isAdmin(loginUser.getUserId())) {
                isCurrentOrg = false;
            }
        } else {
            final long count = roles.stream().filter(role -> {
                if (StringUtils.hasLength(role.getDataScope())) {
                    return role.getDataScope().equals(DataScopeType.ALL.getName()) || role.getDataScope().equals(DataScopeType.ORG_ALL.getName());
                }
                return false;
            }).count();
            isCurrentOrg = count < 1;
        }
        if (isCurrentOrg) {
            return currentOrgId.equals(orgId);
        }
        final TreeClService treeClService = SpringContextHolder.getBean(TreeClService.class);
        TreeClDTO query = new TreeClDTO("sys_org");
        query.setParam(currentOrgId);
        final Set<TreeClModel> treeCl = treeClService.getTreeClByPid(query);
        if (null == treeCl || treeCl.isEmpty()) {
            return false;
        }
        final Set<String> orgIds = treeCl.stream().map(TreeClModel::getId).collect(Collectors.toSet());
        return orgIds.contains(orgId);
    }
}
